package com.bootdo.clouddoadmin.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;

/**
 * 授权服务器配置
 * @author bootdo
 */
@Configuration
@EnableAuthorizationServer //开启授权服务器
public class Oauth2ServiceConfig extends AuthorizationServerConfigurerAdapter {
    // 自动注入SecurityConfigurerAdapter中的AuthenticationManager
    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    DataSource dataSource;

    //配置客户端详情
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("app")// 客户端名字
                .scopes("app") // 授权范围
                .authorizedGrantTypes("password","authorization_code", "refresh_token") // 允许授权的类型
                .secret(new BCryptPasswordEncoder().encode("123456")); // 该客户端的密钥
    }

    // 配置token申请地址与发放方式(令牌服务)
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
        endpoints.tokenStore(jdbcTokenStore());
    }

    JdbcTokenStore jdbcTokenStore(){
        return new JdbcTokenStore(dataSource);
    }

//    @Bean
//    RedisTokenStore redisTokenStore(){
//        return new RedisTokenStore(connectionFactory);
//    }

    // 配置token端点的访问约束
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                // 开启/oauth/token_key验证端口无权限访问
                .tokenKeyAccess("permitAll()")
                // 开启/oauth/check_token验证端口认证权限访问
//                .checkTokenAccess("isAuthenticated()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }


}
